<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,量化投资,机器学习,kaggle,实例,回归算法," />










<meta name="description" content="项目网址:https:&#x2F;&#x2F;www.kaggle.com&#x2F;c&#x2F;house-prices-advanced-regression-techniques 项目要求:用79个特征预测房价。先加载数据吧。 12345# 加载数据train_df &#x3D; pd.read_csv(&quot;.&#x2F;data&#x2F;train.csv&quot;)test_df &#x3D; pd.read_csv(&quot;.&#x2F;data&#x2F;test">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记39——机器学习实操2:回归分析">
<meta property="og:url" content="https://zwdnet.github.io/2020/04/07/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B039%E2%80%94%E2%80%94%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E5%AE%9E%E6%93%8D2-%E5%9B%9E%E5%BD%92%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="项目网址:https:&#x2F;&#x2F;www.kaggle.com&#x2F;c&#x2F;house-prices-advanced-regression-techniques 项目要求:用79个特征预测房价。先加载数据吧。 12345# 加载数据train_df &#x3D; pd.read_csv(&quot;.&#x2F;data&#x2F;train.csv&quot;)test_df &#x3D; pd.read_csv(&quot;.&#x2F;data&#x2F;test">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/05.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/07.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/08.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/09.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/10.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/11.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/12.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/13.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/14.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/15.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/16.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/17.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-04-07T05:44:32.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="机器学习">
<meta property="article:tag" content="kaggle">
<meta property="article:tag" content="实例">
<meta property="article:tag" content="回归算法">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/04/07/量化投资学习笔记39——机器学习实操2-回归分析/"/>





  <title>量化投资学习笔记39——机器学习实操2:回归分析 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/04/07/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B039%E2%80%94%E2%80%94%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E5%AE%9E%E6%93%8D2-%E5%9B%9E%E5%BD%92%E5%88%86%E6%9E%90/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记39——机器学习实操2:回归分析</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-04-07T05:44:32+00:00">
                2020-04-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  18
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>项目网址:<a target="_blank" rel="noopener" href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques">https://www.kaggle.com/c/house-prices-advanced-regression-techniques</a></p>
<p>项目要求:用79个特征预测房价。<br>先加载数据吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 加载数据</span></span><br><span class="line">train_df = pd.read_csv(<span class="string">&quot;./data/train.csv&quot;</span>)</span><br><span class="line">test_df = pd.read_csv(<span class="string">&quot;./data/test.csv&quot;</span>)</span><br><span class="line">print(train_df.info())</span><br><span class="line">print(test_df.info())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/01.png"><br>有81列数据，其中一列是预测目标即房价，其它80列为特征。有很多缺失值。<br>把训练集和测试集合并到一起，进行特征工程。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 将训练数据和训练数据合并到一起</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">concat_df</span>(<span class="params">train_data, test_data</span>):</span></span><br><span class="line"> test_data[<span class="string">&quot;SalePrice&quot;</span>] = <span class="number">0.0</span></span><br><span class="line"> <span class="keyword">return</span> pd.concat([train_data, test_data], sort = <span class="literal">True</span>).reset_index(drop = <span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将训练集与测试集数据合并</span></span><br><span class="line">all_df = concat_df(train_df, test_df)</span><br><span class="line">all_df_backup = all_df.copy(deep = <span class="literal">True</span>)</span><br><span class="line">print(all_df.info())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/02.png"><br>下面进行数据处理，先用最简单的方法，抛弃所有有缺失值的特征。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 数据处理</span></span><br><span class="line"><span class="comment"># 丢弃所有有缺失值的特征</span></span><br><span class="line">all_df = all_df.dropna(axis = <span class="number">1</span>)</span><br><span class="line">print(all_df.info())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/03.png"><br>只剩47列了，剩下的都丢弃了。<br>现在再将数据拆分为训练集和测试集。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 将数据集重新分割为训练集和测试集</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">divide_df</span>(<span class="params">all_data</span>):</span></span><br><span class="line">    <span class="keyword">return</span> all_data.loc[:<span class="number">1459</span>], all_data.loc[<span class="number">1460</span>:].drop([<span class="string">&quot;SalePrice&quot;</span>], axis = <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"> <span class="comment"># 将数据拆分</span></span><br><span class="line"> train_df, test_df = divide_df(all_df)</span><br><span class="line"> print(<span class="string">&quot;训练集:&quot;</span>, train_df.info())</span><br><span class="line"> print(<span class="string">&quot;测试集:&quot;</span>, test_df.info())</span><br></pre></td></tr></table></figure>
<p>接下来进行特征工程，最简单的做法，把所有特征统统选入。但后来发现有的特征不是数值类变量，不能直接用，干脆随便选两个吧。<br>建模，用多元线性回归。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 建模，用多元线性回归。</span></span><br><span class="line">features = train_df.columns</span><br><span class="line"><span class="comment"># features.remove(&quot;SalePrice&quot;)</span></span><br><span class="line"><span class="comment"># features.remove(&quot;Id&quot;)</span></span><br><span class="line">X = train_df.loc[:, [<span class="string">&quot;LotArea&quot;</span>, <span class="string">&quot;MiscVal&quot;</span>]]</span><br><span class="line">Y = train_df.loc[:, <span class="string">&quot;SalePrice&quot;</span>]</span><br><span class="line">X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=<span class="number">0.2</span>, random_state=<span class="number">532</span>)</span><br><span class="line">linreg = LinearRegression()</span><br><span class="line"><span class="comment"># 训练</span></span><br><span class="line">model = linreg.fit(X_train, Y_train)</span><br><span class="line"><span class="comment"># 建模参数</span></span><br><span class="line">print(<span class="string">&quot;模型参数:&quot;</span>, model)</span><br><span class="line">print(<span class="string">&quot;模型截距:&quot;</span>, linreg.intercept_)</span><br><span class="line">print(<span class="string">&quot;参数权重:&quot;</span>, linreg.coef_)</span><br><span class="line">print(<span class="string">&quot;模型评分:&quot;</span>, model.score(X_test, Y_test))</span><br><span class="line"><span class="comment"># 预测</span></span><br><span class="line">y_pred = linreg.predict(X_test)</span><br><span class="line"><span class="comment"># 画图看看</span></span><br><span class="line">plt.figure()</span><br><span class="line"><span class="built_in">id</span> = np.arange(<span class="built_in">len</span>(y_pred))</span><br><span class="line">plt.plot(<span class="built_in">id</span>, Y_test)</span><br><span class="line">plt.scatter(<span class="built_in">id</span>, y_pred)</span><br><span class="line">plt.savefig(<span class="string">&quot;simplestResult.png&quot;</span>)</span><br><span class="line">plt.close()</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/04.png"><br>生成提交文件提交看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 生成提交文件</span></span><br><span class="line">X_test = test_df.loc[:, [<span class="string">&quot;LotArea&quot;</span>, <span class="string">&quot;MiscVal&quot;</span>]]</span><br><span class="line">y = linreg.predict(X_test)</span><br><span class="line">Id = []</span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1461</span>, <span class="number">2920</span>):</span><br><span class="line"> Id.append(x)</span><br><span class="line">res = pd.DataFrame(&#123;<span class="string">&quot;Id&quot;</span>:Id, <span class="string">&quot;SalePrice&quot;</span>:y&#125;)</span><br><span class="line">res.to_csv(<span class="string">&quot;first.csv&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>提交到kaggle看看。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/05.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/06.png"><br>排4217名，果然很差。现在开始改进吧。<br>数据比较复杂，还是看看别人的吧。[1]<br>导入库</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">import</span> seaborn <span class="keyword">as</span> sns</span><br><span class="line">color = sns.color_palette()</span><br><span class="line">sns.set_style(<span class="string">&quot;darkgrid&quot;</span>)</span><br><span class="line"><span class="keyword">import</span> warnings</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">ignore_warn</span>(<span class="params">*args, **kwargs</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">warnings.warn = ignore_warn</span><br><span class="line"><span class="keyword">from</span> scipy <span class="keyword">import</span> stats</span><br><span class="line"><span class="keyword">from</span> scipy.stats <span class="keyword">import</span> norm, skew</span><br><span class="line">pd.set_option(<span class="string">&quot;display.float_format&quot;</span>, <span class="keyword">lambda</span> x:<span class="string">&quot;&#123;:.3f&#125;&quot;</span>.<span class="built_in">format</span>(x))</span><br></pre></td></tr></table></figure>
<p>导入数据，丢弃”Id”列</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 载入数据</span></span><br><span class="line">train = pd.read_csv(<span class="string">&quot;./data/train.csv&quot;</span>)</span><br><span class="line">test = pd.read_csv(<span class="string">&quot;./data/test.csv&quot;</span>)</span><br><span class="line"></span><br><span class="line">print(train.head(<span class="number">5</span>))</span><br><span class="line">print(test.head(<span class="number">5</span>))</span><br><span class="line">print(train.shape)</span><br><span class="line">print(test.shape)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 保存ID值</span></span><br><span class="line">train_ID = train[<span class="string">&quot;Id&quot;</span>]</span><br><span class="line">test_ID = test[<span class="string">&quot;Id&quot;</span>]</span><br><span class="line"><span class="comment"># 从数据中丢弃&quot;Id&quot;列</span></span><br><span class="line">train.drop(<span class="string">&quot;Id&quot;</span>, axis = <span class="number">1</span>, inplace = <span class="literal">True</span>)</span><br><span class="line">test.drop(<span class="string">&quot;Id&quot;</span>, axis = <span class="number">1</span>, inplace = <span class="literal">True</span>)</span><br><span class="line">print(train.shape)</span><br><span class="line">print(test.shape)</span><br></pre></td></tr></table></figure>
<p>接下来寻找异常值，画GrLivArea与房价的关系。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 数据处理</span></span><br><span class="line"><span class="comment"># 探索异常值</span></span><br><span class="line">fig, ax = plt.subplots()</span><br><span class="line">ax.scatter(x = train[<span class="string">&quot;GrLivArea&quot;</span>], y = train[<span class="string">&quot;SalePrice&quot;</span>])</span><br><span class="line">plt.ylabel(<span class="string">&quot;SalePrice&quot;</span>, fontsize = <span class="number">13</span>)</span><br><span class="line">plt.xlabel(<span class="string">&quot;GrLivArea&quot;</span>, fontsize = <span class="number">13</span>)</span><br><span class="line">plt.savefig(<span class="string">&quot;outliers.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/07.png"><br>可以看到右下角有一些异常值，可以删除它们。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 删除异常值</span></span><br><span class="line">train = train.drop(train[(train[<span class="string">&quot;GrLivArea&quot;</span>] &gt; <span class="number">4000</span>) &amp; (train[<span class="string">&#x27;SalePrice&#x27;</span>]&lt;<span class="number">300000</span>)].index)</span><br><span class="line">fig, ax = plt.subplots()</span><br><span class="line">ax.scatter(x = train[<span class="string">&quot;GrLivArea&quot;</span>], y = train[<span class="string">&quot;SalePrice&quot;</span>])</span><br><span class="line">plt.ylabel(<span class="string">&quot;SalePrice&quot;</span>, fontsize = <span class="number">13</span>)</span><br><span class="line">plt.xlabel(<span class="string">&quot;GrLivArea&quot;</span>, fontsize = <span class="number">13</span>)</span><br><span class="line">plt.savefig(<span class="string">&quot;outliers_afterdel.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/08.png"><br>不能总是这么删除异常值，尤其是测试集上也有异常值时。<br>再来分析一下目标变量:SalePrice。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 研究目标变量SalePrice</span></span><br><span class="line">plt.figure()</span><br><span class="line">sns.distplot(train[<span class="string">&quot;SalePrice&quot;</span>], fit = norm)</span><br><span class="line">(mu, sigma) = norm.fit(train[<span class="string">&quot;SalePrice&quot;</span>])</span><br><span class="line">print(<span class="string">&quot;mu = &#123;:.2f&#125; and sigma = &#123;:.2f&#125;\n&quot;</span>.<span class="built_in">format</span>(mu, sigma))</span><br><span class="line">plt.title(<span class="string">&quot;SalePrice distribution&quot;</span>)</span><br><span class="line">plt.savefig(<span class="string">&quot;SalePriceDist.png&quot;</span>)</span><br><span class="line">fig = plt.figure()</span><br><span class="line">res = stats.probplot(train[<span class="string">&quot;SalePrice&quot;</span>], plot = plt)</span><br><span class="line">plt.savefig(<span class="string">&quot;SalePriceProb.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/09.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/10.png"><br>数据是右偏的，而线性模型希望数据是正态分布的，因此需要对数据进行处理。<br>对数据进行对数转换。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 对SalePrice进行对数转换</span></span><br><span class="line">train[<span class="string">&quot;SalePrice&quot;</span>] = np.log1p(train[<span class="string">&quot;SalePrice&quot;</span>])</span><br><span class="line"><span class="comment"># 再画图</span></span><br><span class="line">plt.figure()</span><br><span class="line">sns.distplot(train[<span class="string">&quot;SalePrice&quot;</span>], fit = norm)</span><br><span class="line">(mu, sigma) = norm.fit(train[<span class="string">&quot;SalePrice&quot;</span>])</span><br><span class="line">print(<span class="string">&quot;mu = &#123;:.2f&#125; and sigma = &#123;:.2f&#125;\n&quot;</span>.<span class="built_in">format</span>(mu, sigma))</span><br><span class="line">plt.title(<span class="string">&quot;SalePrice distribution&quot;</span>)</span><br><span class="line">plt.savefig(<span class="string">&quot;SalePriceDist2.png&quot;</span>)</span><br><span class="line">fig = plt.figure()</span><br><span class="line">res = stats.probplot(train[<span class="string">&quot;SalePrice&quot;</span>], plot = plt)</span><br><span class="line">plt.savefig(<span class="string">&quot;SalePriceProb2.png&quot;</span>)</span><br><span class="line">plt.close()</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/11.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/12.png"><br>OK了，比处理以前好多了。<br>下面进行特征工程。<br>首先将训练集数据和测试集数据合并到一起。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 将训练集和测试集合并到一起</span></span><br><span class="line">ntrain = train.shape[<span class="number">0</span>]</span><br><span class="line">ntest = test.shape[<span class="number">0</span>]</span><br><span class="line">y_train = train.SalePrice.values</span><br><span class="line">all_data = pd.concat((train, test)).reset_index(drop = <span class="literal">True</span>)</span><br><span class="line">all_data.drop([<span class="string">&quot;SalePrice&quot;</span>], axis = <span class="number">1</span>, inplace = <span class="literal">True</span>)</span><br><span class="line">print(<span class="string">&quot;all_data的大小为:&#123;&#125;&quot;</span>.<span class="built_in">format</span>(all_data.shape))</span><br></pre></td></tr></table></figure>
<p>看看缺失值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 处理缺失值</span></span><br><span class="line">all_data_na = (all_data.isnull().<span class="built_in">sum</span>()/<span class="built_in">len</span>(all_data))*<span class="number">100</span></span><br><span class="line">all_data_na = all_data_na.drop(all_data_na[all_data_na == <span class="number">0</span>].index).sort_values(ascending = <span class="literal">False</span>)[:<span class="number">30</span>]</span><br><span class="line">missing_data = pd.DataFrame(&#123;<span class="string">&quot;Missing Ratio&quot;</span> : all_data_na&#125;)</span><br><span class="line">print(missing_data.head(<span class="number">20</span>))</span><br></pre></td></tr></table></figure>
<p>缺失值比例<br>Missing Ratio<br>PoolQC               99.691<br>MiscFeature          96.400<br>Alley                93.212<br>Fence                80.425<br>FireplaceQu          48.680<br>LotFrontage          16.661<br>GarageQual            5.451<br>GarageCond            5.451<br>GarageFinish          5.451<br>GarageYrBlt           5.451<br>GarageType            5.382<br>BsmtExposure          2.811<br>BsmtCond              2.811<br>BsmtQual              2.777<br>BsmtFinType2          2.743<br>BsmtFinType1          2.708<br>MasVnrType            0.823<br>MasVnrArea            0.788<br>MSZoning              0.137<br>BsmtFullBath          0.069<br>再画图看看</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 画图看看</span></span><br><span class="line">f, ax = plt.subplots(figsize = (<span class="number">15</span>, <span class="number">12</span>))</span><br><span class="line">plt.xticks(rotation = <span class="string">&quot;90&quot;</span>)</span><br><span class="line">sns.barplot(x = all_data_na.index, y = all_data_na)</span><br><span class="line">plt.xlabel(<span class="string">&#x27;Features&#x27;</span>, fontsize=<span class="number">15</span>)</span><br><span class="line">plt.ylabel(<span class="string">&#x27;Percent of missing values&#x27;</span>, fontsize=<span class="number">15</span>)</span><br><span class="line">plt.title(<span class="string">&#x27;Percent missing data by feature&#x27;</span>, fontsize=<span class="number">15</span>)</span><br><span class="line">plt.savefig(<span class="string">&quot;Missingdata.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/13.png"><br>绘图看看特征与SalePrice的相关性。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 特征与SalePrice的相关性</span></span><br><span class="line">corrmat = train.corr()</span><br><span class="line">plt.subplots(figsize=(<span class="number">12</span>,<span class="number">9</span>))</span><br><span class="line">sns.heatmap(corrmat, vmax = <span class="number">0.9</span>, square = <span class="literal">True</span>)</span><br><span class="line">plt.savefig(<span class="string">&quot;corrmat.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/14.png"><br>具体处理缺失值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 处理缺失值</span></span><br><span class="line"><span class="comment"># PoolQC 缺失值代表没游泳池</span></span><br><span class="line">all_data[<span class="string">&quot;PoolQC&quot;</span>] = all_data[<span class="string">&quot;PoolQC&quot;</span>].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># MiscFeature 缺失值代表没该特征</span></span><br><span class="line">all_data[<span class="string">&quot;MiscFeature&quot;</span>] = all_data[<span class="string">&quot;MiscFeature&quot;</span>].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># Alley 缺失值代表没有小巷入口</span></span><br><span class="line">all_data[<span class="string">&quot;Alley&quot;</span>] = all_data[<span class="string">&quot;Alley&quot;</span>].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># Fence 缺失值代表没栅栏</span></span><br><span class="line">all_data[<span class="string">&quot;Fence&quot;</span>] = all_data[<span class="string">&quot;Fence&quot;</span>].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># FireplaceQu 缺失值代表没壁炉</span></span><br><span class="line">all_data[<span class="string">&quot;FireplaceQu&quot;</span>] = all_data[<span class="string">&quot;FireplaceQu&quot;</span>].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># LotFrontage 用其邻居的临街面积的中位数填充缺失值</span></span><br><span class="line">all_data[<span class="string">&quot;LotFrontage&quot;</span>] = all_data.groupby(<span class="string">&quot;Neighborhood&quot;</span>)[<span class="string">&quot;LotFrontage&quot;</span>].transform(<span class="keyword">lambda</span> x : x.fillna(x.median()))</span><br><span class="line">   </span><br><span class="line"><span class="comment"># GarageType, GarageFinish, GarageQual and GarageCond 都替换为None</span></span><br><span class="line"><span class="keyword">for</span> col <span class="keyword">in</span> (<span class="string">&#x27;GarageType&#x27;</span>, <span class="string">&#x27;GarageFinish&#x27;</span>, <span class="string">&#x27;GarageQual&#x27;</span>, <span class="string">&#x27;GarageCond&#x27;</span>):</span><br><span class="line">    all_data[col] = all_data[col].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># GarageYrBlt, GarageArea and GarageCars 替换为0</span></span><br><span class="line"><span class="keyword">for</span> col <span class="keyword">in</span> (<span class="string">&#x27;GarageYrBlt&#x27;</span>, <span class="string">&#x27;GarageArea&#x27;</span>, <span class="string">&#x27;GarageCars&#x27;</span>):</span><br><span class="line">    all_data[col] = all_data[col].fillna(<span class="number">0</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># BsmtFinSF1, BsmtFinSF2, BsmtUnfSF, TotalBsmtSF, BsmtFullBath and BsmtHalfBath 没有地下室，置为0</span></span><br><span class="line"><span class="keyword">for</span> col <span class="keyword">in</span> (<span class="string">&#x27;BsmtFinSF1&#x27;</span>, <span class="string">&#x27;BsmtFinSF2&#x27;</span>, <span class="string">&#x27;BsmtUnfSF&#x27;</span>,<span class="string">&#x27;TotalBsmtSF&#x27;</span>, <span class="string">&#x27;BsmtFullBath&#x27;</span>, <span class="string">&#x27;BsmtHalfBath&#x27;</span>):</span><br><span class="line">    all_data[col] = all_data[col].fillna(<span class="number">0</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># BsmtQual, BsmtCond, BsmtExposure, BsmtFinType1 and BsmtFinType2 没有地下室，置为None</span></span><br><span class="line"><span class="keyword">for</span> col <span class="keyword">in</span> (<span class="string">&#x27;BsmtQual&#x27;</span>, <span class="string">&#x27;BsmtCond&#x27;</span>, <span class="string">&#x27;BsmtExposure&#x27;</span>, <span class="string">&#x27;BsmtFinType1&#x27;</span>, <span class="string">&#x27;BsmtFinType2&#x27;</span>):</span><br><span class="line">    all_data[col] = all_data[col].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># MasVnrArea and MasVnrType 缺失值代表没有砖石覆盖，z置为0和None</span></span><br><span class="line">all_data[<span class="string">&quot;MasVnrType&quot;</span>] = all_data[<span class="string">&quot;MasVnrType&quot;</span>].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">all_data[<span class="string">&quot;MasVnrArea&quot;</span>] = all_data[<span class="string">&quot;MasVnrArea&quot;</span>].fillna(<span class="number">0</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># MSZoning 用最多的值&quot;RL&quot;代替</span></span><br><span class="line">all_data[<span class="string">&#x27;MSZoning&#x27;</span>] = all_data[<span class="string">&#x27;MSZoning&#x27;</span>].fillna(all_data[<span class="string">&#x27;MSZoning&#x27;</span>].mode()[<span class="number">0</span>])</span><br><span class="line">   </span><br><span class="line"><span class="comment"># Utilities大多数值为AllPub，只有一个NoSeWa和两个NA，由于NoSeWa只在训练集中出现，可以安全去除。</span></span><br><span class="line">all_data = all_data.drop([<span class="string">&#x27;Utilities&#x27;</span>], axis=<span class="number">1</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># Functional缺失值代表是典型的。</span></span><br><span class="line">all_data[<span class="string">&quot;Functional&quot;</span>] = all_data[<span class="string">&quot;Functional&quot;</span>].fillna(<span class="string">&quot;Typ&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># Electrical只有一个缺失值，用众数代替</span></span><br><span class="line">all_data[<span class="string">&#x27;Electrical&#x27;</span>] = all_data[<span class="string">&#x27;Electrical&#x27;</span>].fillna(all_data[<span class="string">&#x27;Electrical&#x27;</span>].mode()[<span class="number">0</span>])</span><br><span class="line">   </span><br><span class="line"><span class="comment"># KitchenQual只有一个缺失值，用众数代替</span></span><br><span class="line">all_data[<span class="string">&#x27;KitchenQual&#x27;</span>] = all_data[<span class="string">&#x27;KitchenQual&#x27;</span>].fillna(all_data[<span class="string">&#x27;KitchenQual&#x27;</span>].mode()[<span class="number">0</span>])</span><br><span class="line">   </span><br><span class="line"><span class="comment"># Exterior1st and Exterior2nd 用众数代替</span></span><br><span class="line">all_data[<span class="string">&#x27;Exterior1st&#x27;</span>] = all_data[<span class="string">&#x27;Exterior1st&#x27;</span>].fillna(all_data[<span class="string">&#x27;Exterior1st&#x27;</span>].mode()[<span class="number">0</span>])</span><br><span class="line">all_data[<span class="string">&#x27;Exterior2nd&#x27;</span>] = all_data[<span class="string">&#x27;Exterior2nd&#x27;</span>].fillna(all_data[<span class="string">&#x27;Exterior2nd&#x27;</span>].mode()[<span class="number">0</span>])</span><br><span class="line">   </span><br><span class="line"><span class="comment"># SaleType 用众数填充</span></span><br><span class="line">all_data[<span class="string">&#x27;SaleType&#x27;</span>] = all_data[<span class="string">&#x27;SaleType&#x27;</span>].fillna(all_data[<span class="string">&#x27;SaleType&#x27;</span>].mode()[<span class="number">0</span>])</span><br><span class="line">   </span><br><span class="line"><span class="comment"># MSSubClass 用None填充</span></span><br><span class="line">all_data[<span class="string">&#x27;MSSubClass&#x27;</span>] = all_data[<span class="string">&#x27;MSSubClass&#x27;</span>].fillna(<span class="string">&quot;None&quot;</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># OK，再看看有没有缺失值的</span></span><br><span class="line">all_data_na = (all_data.isnull().<span class="built_in">sum</span>()/<span class="built_in">len</span>(all_data))*<span class="number">100</span></span><br><span class="line">all_data_na = all_data_na.drop(all_data_na[all_data_na == <span class="number">0</span>].index).sort_values(ascending = <span class="literal">False</span>)[:<span class="number">30</span>]</span><br><span class="line">missing_data = pd.DataFrame(&#123;<span class="string">&quot;Missing Ratio&quot;</span> : all_data_na&#125;)</span><br><span class="line">print(missing_data.head())</span><br></pre></td></tr></table></figure>
<p>没有缺失值了。<br>接着进行进一步的特征工程。<br>转换实际上是分类变量的数值变量</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 转换实际上是分类变量的数值变量</span></span><br><span class="line"><span class="comment"># MSSubClass</span></span><br><span class="line">all_data[<span class="string">&#x27;MSSubClass&#x27;</span>] = all_data[<span class="string">&#x27;MSSubClass&#x27;</span>].apply(<span class="built_in">str</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># OverallCond</span></span><br><span class="line">all_data[<span class="string">&#x27;OverallCond&#x27;</span>] = all_data[<span class="string">&#x27;OverallCond&#x27;</span>].astype(<span class="built_in">str</span>)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># 售卖年份和月份</span></span><br><span class="line">all_data[<span class="string">&#x27;YrSold&#x27;</span>] = all_data[<span class="string">&#x27;YrSold&#x27;</span>].astype(<span class="built_in">str</span>)</span><br><span class="line">all_data[<span class="string">&#x27;MoSold&#x27;</span>] = all_data[<span class="string">&#x27;MoSold&#x27;</span>].astype(<span class="built_in">str</span>)</span><br></pre></td></tr></table></figure>
<p>对一些分类变量进行标签编码。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 对一些分类变量进行标签编码</span></span><br><span class="line">cols = (<span class="string">&#x27;FireplaceQu&#x27;</span>, <span class="string">&#x27;BsmtQual&#x27;</span>, <span class="string">&#x27;BsmtCond&#x27;</span>, <span class="string">&#x27;GarageQual&#x27;</span>, <span class="string">&#x27;GarageCond&#x27;</span>, </span><br><span class="line">    <span class="string">&#x27;ExterQual&#x27;</span>, <span class="string">&#x27;ExterCond&#x27;</span>,<span class="string">&#x27;HeatingQC&#x27;</span>, <span class="string">&#x27;PoolQC&#x27;</span>, <span class="string">&#x27;KitchenQual&#x27;</span>, <span class="string">&#x27;BsmtFinType1&#x27;</span>, </span><br><span class="line">    <span class="string">&#x27;BsmtFinType2&#x27;</span>, <span class="string">&#x27;Functional&#x27;</span>, <span class="string">&#x27;Fence&#x27;</span>, <span class="string">&#x27;BsmtExposure&#x27;</span>, <span class="string">&#x27;GarageFinish&#x27;</span>, <span class="string">&#x27;LandSlope&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;LotShape&#x27;</span>, <span class="string">&#x27;PavedDrive&#x27;</span>, <span class="string">&#x27;Street&#x27;</span>, <span class="string">&#x27;Alley&#x27;</span>, <span class="string">&#x27;CentralAir&#x27;</span>, <span class="string">&#x27;MSSubClass&#x27;</span>, <span class="string">&#x27;OverallCond&#x27;</span>, </span><br><span class="line">    <span class="string">&#x27;YrSold&#x27;</span>, <span class="string">&#x27;MoSold&#x27;</span>)</span><br><span class="line"><span class="keyword">for</span> c <span class="keyword">in</span> cols:</span><br><span class="line">    lbl = LabelEncoder()</span><br><span class="line">    lbl.fit(<span class="built_in">list</span>(all_data[c].values))</span><br><span class="line">    </span><br><span class="line">    all_data[c] = lbl.transform(<span class="built_in">list</span>(all_data[c].values))</span><br><span class="line">    </span><br><span class="line">print(<span class="string">&#x27;Shape all_data: &#123;&#125;&#x27;</span>.<span class="built_in">format</span>(all_data.shape))</span><br></pre></td></tr></table></figure>
<p>再新增一个特征，将所有面积数相加。<br>接着处理偏态特征</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 将所有面积特征相加</span></span><br><span class="line">all_data[<span class="string">&#x27;TotalSF&#x27;</span>] = all_data[<span class="string">&#x27;TotalBsmtSF&#x27;</span>] + all_data[<span class="string">&#x27;1stFlrSF&#x27;</span>] + all_data[<span class="string">&#x27;2ndFlrSF&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 处理偏态特征</span></span><br><span class="line">numeric_feats = all_data.dtypes[all_data.dtypes != <span class="string">&quot;object&quot;</span>].index</span><br><span class="line"><span class="comment"># 检查所有数值特征的偏态性</span></span><br><span class="line">skewed_feats = all_data[numeric_feats].apply(<span class="keyword">lambda</span> x: skew(x.dropna())).sort_values(ascending=<span class="literal">False</span>)</span><br><span class="line">print(<span class="string">&quot;数值特征的偏态性:&quot;</span>)</span><br><span class="line">skewness = pd.DataFrame(&#123;<span class="string">&#x27;Skew&#x27;</span> :skewed_feats&#125;)</span><br><span class="line">print(skewness.head(<span class="number">10</span>))</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/15.png"><br>对高偏态数据进行Box Cox转换。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 进行Box Cox转换</span></span><br><span class="line">skewness = skewness[<span class="built_in">abs</span>(skewness) &gt; <span class="number">0.75</span>]</span><br><span class="line">print(<span class="string">&quot;有&#123;&#125;个数值特征要进行Box Cox转换&quot;</span>.<span class="built_in">format</span>(skewness.shape[<span class="number">0</span>]))</span><br><span class="line">   </span><br><span class="line"><span class="keyword">from</span> scipy.special <span class="keyword">import</span> boxcox1p</span><br><span class="line">skewed_features = skewness.index</span><br><span class="line">lam = <span class="number">0.15</span></span><br><span class="line">   </span><br><span class="line"><span class="keyword">for</span> feat <span class="keyword">in</span> skewed_features:</span><br><span class="line">    all_data[feat] = boxcox1p(all_data[feat], lam)</span><br><span class="line">all_data = pd.get_dummies(all_data)</span><br><span class="line">print(all_data.shape)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># 最后，重新划分训练集和测试集</span></span><br><span class="line">train = all_data[:ntrain]</span><br><span class="line">test = all_data[ntrain:]</span><br></pre></td></tr></table></figure>
<p>然后进行建模了。<br>先导入相关的库。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.linear_model <span class="keyword">import</span> ElasticNet, Lasso,  BayesianRidge, LassoLarsIC</span><br><span class="line"><span class="keyword">from</span> sklearn.ensemble <span class="keyword">import</span> RandomForestRegressor,  GradientBoostingRegressor</span><br><span class="line"><span class="keyword">from</span> sklearn.kernel_ridge <span class="keyword">import</span> KernelRidge</span><br><span class="line"><span class="keyword">from</span> sklearn.pipeline <span class="keyword">import</span> make_pipeline</span><br><span class="line"><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> RobustScaler</span><br><span class="line"><span class="keyword">from</span> sklearn.base <span class="keyword">import</span> BaseEstimator, TransformerMixin, RegressorMixin, clone</span><br><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> KFold, cross_val_score, train_test_split</span><br><span class="line"><span class="keyword">from</span> sklearn.metrics <span class="keyword">import</span> mean_squared_error</span><br><span class="line"><span class="keyword">import</span> xgboost <span class="keyword">as</span> xgb</span><br><span class="line"><span class="keyword">import</span> lightgbm <span class="keyword">as</span> lgb</span><br></pre></td></tr></table></figure>
<p>接着定义一个交叉验证策略<br>使用sklearn的cross_val_score函数，在这之前先将数据打乱。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 先建立交叉验证策略</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">rmsle_cv</span>(<span class="params">model, train</span>):</span></span><br><span class="line">    n_folds = <span class="number">5</span></span><br><span class="line">    y_train = train.SalePrice.values</span><br><span class="line">    kf = kFold(n_folds, shuffle=<span class="literal">True</span>, random_state = <span class="number">42</span>).get_n_splits(train.values)</span><br><span class="line">    rmse = np.sqrt(-cross_val_score(model, train.values, y_train, scoring=<span class="string">&quot;neg_mean_squared_error&quot;</span>, cv = kf)))</span><br><span class="line">    <span class="keyword">return</span>(rmse)</span><br></pre></td></tr></table></figure>
<p>接下来就正式开始建模了，拉索回归(LASSO Regression)对异常值比较敏感，使用sklearn的Robustscaler()函数来处理。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 建模</span></span><br><span class="line"><span class="comment"># LASSO回归</span></span><br><span class="line">lasso = make_pipeline(RobustScaler(), Lasso(alpha =<span class="number">0.0005</span>, random_state=<span class="number">1</span>))</span><br><span class="line"><span class="comment"># 塑性网络回归 Elastic Net Regression</span></span><br><span class="line">ENet = make_pipeline(RobustScaler(), ElasticNet(alpha=<span class="number">0.0005</span>, l1_ratio=<span class="number">.9</span>, random_state=<span class="number">3</span>))</span><br><span class="line"><span class="comment"># 核心岭回归 Kernel Ridge Regression</span></span><br><span class="line">KRR = KernelRidge(alpha=<span class="number">0.6</span>, kernel=<span class="string">&#x27;polynomial&#x27;</span>, degree=<span class="number">2</span>, coef0=<span class="number">2.5</span>)</span><br><span class="line"><span class="comment"># Gradient Boosting Regression</span></span><br><span class="line"><span class="comment"># 使用huber来增强对异常值的健壮性</span></span><br><span class="line">GBoost = GradientBoostingRegressor(n_estimators=<span class="number">3000</span>, learning_rate=<span class="number">0.05</span>, max_depth=<span class="number">4</span>, max_features=<span class="string">&#x27;sqrt&#x27;</span>, min_samples_leaf=<span class="number">15</span>, min_samples_split=<span class="number">10</span>, loss=<span class="string">&#x27;huber&#x27;</span>, random_state =<span class="number">5</span>)</span><br><span class="line"><span class="comment"># XGBoost</span></span><br><span class="line">model_xgb = xgb.XGBRegressor(colsample_bytree=<span class="number">0.4603</span>, gamma=<span class="number">0.0468</span>, learning_rate=<span class="number">0.05</span>, max_depth=<span class="number">3</span>, min_child_weight=<span class="number">1.7817</span>, n_estimators=<span class="number">2200</span>, reg_alpha=<span class="number">0.4640</span>, reg_lambda=<span class="number">0.8571</span>, subsample=<span class="number">0.5213</span>, silent=<span class="number">1</span>, random_state =<span class="number">7</span>, nthread = -<span class="number">1</span>)</span><br><span class="line"><span class="comment">#LightGBM</span></span><br><span class="line">model_lgb = lgb.LGBMRegressor(objective=<span class="string">&#x27;regression&#x27;</span>,num_leaves=<span class="number">5</span>, learning_rate=<span class="number">0.05</span>, n_estimators=<span class="number">720</span>, max_bin = <span class="number">55</span>, bagging_fraction = <span class="number">0.8</span>, bagging_freq = <span class="number">5</span>, feature_fraction = <span class="number">0.2319</span>, feature_fraction_seed=<span class="number">9</span>, bagging_seed=<span class="number">9</span>, min_data_in_leaf =<span class="number">6</span>, min_sum_hessian_in_leaf = <span class="number">11</span>)</span><br><span class="line"><span class="comment"># 看一下这些模型的评分</span></span><br><span class="line">models = [lasso, ENet, KRR, GBoost, model_xgb, model_lgb]</span><br><span class="line">names = [<span class="string">&quot;lasso&quot;</span>, <span class="string">&quot;ENet&quot;</span>, <span class="string">&quot;KRR&quot;</span>, <span class="string">&quot;GBoost&quot;</span>, <span class="string">&quot;model_xgb&quot;</span>, <span class="string">&quot;model_lgb&quot;</span>]</span><br><span class="line">n = <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> model <span class="keyword">in</span> models:</span><br><span class="line">    score = rmsle_cv(model, train, y_train)</span><br><span class="line">    print(<span class="string">&quot;\n&#123;&#125; score: &#123;:.4f&#125; (&#123;:.4f&#125;)\n&quot;</span>.<span class="built_in">format</span>(names[n], score.mean(), score.std()))</span><br><span class="line">    n += <span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>结果<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/16.png"><br>下面进行模型堆栈。<br>最简单的方法，将基本模型取均值。<br>创建一个类来实现。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 模型堆栈,求模型平均值</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AveragingModels</span>(<span class="params">BaseEstimator, RegressorMixin, TransformerMixin</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, models</span>):</span></span><br><span class="line">        self.models = models</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 用训练数据训练模型</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">fit</span>(<span class="params">self, X, y</span>):</span></span><br><span class="line">        self.models_ = [clone(x) <span class="keyword">for</span> x <span class="keyword">in</span> self.models]</span><br><span class="line">       </span><br><span class="line">        <span class="keyword">for</span> model <span class="keyword">in</span> self.models_:</span><br><span class="line">            model.fit(X, y)</span><br><span class="line">           </span><br><span class="line">        <span class="keyword">return</span> self</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 做出预测并取平均值</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">predict</span>(<span class="params">self, X</span>):</span></span><br><span class="line">        predictions = np.column_stack([model.predict(X) <span class="keyword">for</span> model <span class="keyword">in</span> self.models_])</span><br><span class="line">        <span class="keyword">return</span> np.mean(predictions, axis=<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 求模型的平均值</span></span><br><span class="line">    averaged_models = AveragingModels(models = (lasso, ENet, KRR, GBoost, model_xgb, model_lgb))</span><br><span class="line">    score = rmsle_cv(averaged_models, train, y_train)</span><br><span class="line">    print(<span class="string">&quot;平均基本模型得分为: &#123;:.4f&#125; (&#123;:.4f&#125;)\n&quot;</span>.<span class="built_in">format</span>(score.mean(), score.std()))</span><br></pre></td></tr></table></figure>
<p>结果:<br>平均基本模型得分为: 0.1085 (0.0070)<br>下面进行更复杂一些的stacking。在平均基本模型上增加一个元模型，并用基础模型的预测来训练元模型。<br>分四步:<br>①将训练集划分为两个互斥的部分<br>②用其中的一部分训练众多基本模型<br>③用另一部分进行测试。<br>④用第三步的预测作为输入，正确的目标变量作为输出训练更高级的成为元模型的学习器。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 加入元模型的stacking</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StackingAveragedModels</span>(<span class="params">BaseEstimator, RegressorMixin, TransformerMixin</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, base_models, meta_model, n_folds=<span class="number">5</span></span>):</span></span><br><span class="line">        self.base_models = base_models</span><br><span class="line">        self.meta_model = meta_model</span><br><span class="line">        self.n_folds = n_folds</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 拟合模型</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">fit</span>(<span class="params">self, X, y</span>):</span></span><br><span class="line">        self.base_models_ = [<span class="built_in">list</span>() <span class="keyword">for</span> x <span class="keyword">in</span> self.base_models]</span><br><span class="line">        self.meta_model_ = clone(self.meta_model)</span><br><span class="line">        kfold = KFold(n_splits=self.n_folds, shuffle=<span class="literal">True</span>, random_state=<span class="number">156</span>)</span><br><span class="line">       </span><br><span class="line">        <span class="comment"># 训练模型，做出预测</span></span><br><span class="line">        out_of_fold_predictions = np.zeros((X.shape[<span class="number">0</span>], <span class="built_in">len</span>(self.base_models)))</span><br><span class="line">        <span class="keyword">for</span> i, model <span class="keyword">in</span> <span class="built_in">enumerate</span>(self.base_models):</span><br><span class="line">            <span class="keyword">for</span> train_index, holdout_index <span class="keyword">in</span> kfold.split(X, y):</span><br><span class="line">                instance = clone(model)</span><br><span class="line">                self.base_models_[i].append(instance)</span><br><span class="line">                instance.fit(X[train_index], y[train_index])</span><br><span class="line">                y_pred = instance.predict(X[holdout_index])</span><br><span class="line">                out_of_fold_predictions[holdout_index, i] = y_pred</span><br><span class="line">       </span><br><span class="line">        self.meta_model_.fit(out_of_fold_predictions, y)</span><br><span class="line">        <span class="keyword">return</span> self</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 使用所有基本模型的测试结果作为元数据训练元模型</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">predict</span>(<span class="params">self, X</span>):</span></span><br><span class="line">        meta_features = np.column_stack([np.column_stack([model.predict(X) <span class="keyword">for</span> model <span class="keyword">in</span> base_models]).mean(axis=<span class="number">1</span>) <span class="keyword">for</span> base_models <span class="keyword">in</span> self.base_models_ ])</span><br><span class="line">        <span class="keyword">return</span> self.meta_model_.predict(meta_features)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 更复杂的Stacking，增加元模型</span></span><br><span class="line">    stack_averaged_models = StackingAveragedModels(base_models = (ENet, KRR, GBoost, model_xgb, model_lgb), meta_model = lasso)</span><br><span class="line">    score = rmsle_cv(stack_averaged_models, train, y_train)</span><br><span class="line">    print(<span class="string">&quot;元模型得分为: &#123;:.4f&#125; (&#123;:.4f&#125;)\n&quot;</span>.<span class="built_in">format</span>(score.mean(), score.std()))</span><br></pre></td></tr></table></figure>
<p>结果为<br>元模型得分为: 0.1085 (0.0070)<br>跟原来一样(原文没有把全部模型加入)<br>最后进行预测生成提交文件</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 生成预测</span></span><br><span class="line"><span class="comment"># 先定义评估函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">rmsle</span>(<span class="params">y, y_pred</span>):</span></span><br><span class="line">    <span class="keyword">return</span> np.sqrt(mean_squared_error(y, y_pred))</span><br><span class="line">   </span><br><span class="line"><span class="comment"># StackedRegressor</span></span><br><span class="line">stacked_averaged_models.fit(train.values, y_train)</span><br><span class="line">stacked_train_pred = stacked_averaged_models.predict(train.values)</span><br><span class="line">stacked_pred = np.expm1(stacked_averaged_models.predict(test.values))</span><br><span class="line">print(rmsle(y_train, stacked_train_pred))</span><br><span class="line"><span class="comment"># XGBoost</span></span><br><span class="line">model_xgb.fit(train, y_train)</span><br><span class="line">xgb_train_pred = model_xgb.predict(train)</span><br><span class="line">xgb_pred = np.expm1(model_xgb.predict(test))</span><br><span class="line">print(rmsle(y_train, xgb_train_pred))</span><br><span class="line"><span class="comment"># LightGBM</span></span><br><span class="line">model_lgb.fit(train, y_train)</span><br><span class="line">lgb_train_pred = model_lgb.predict(train)</span><br><span class="line">lgb_pred = np.expm1(model_lgb.predict(test.values))</span><br><span class="line">print(rmsle(y_train, lgb_train_pred))</span><br><span class="line"><span class="comment"># 几个模型的加权评分</span></span><br><span class="line">print(<span class="string">&#x27;RMSLE score on train data:&#x27;</span>)</span><br><span class="line">print(rmsle(y_train,stacked_train_pred*<span class="number">0.70</span> + xgb_train_pred*<span class="number">0.15</span> + lgb_train_pred*<span class="number">0.15</span> ))</span><br><span class="line"><span class="comment"># 形成预测</span></span><br><span class="line">ensemble = stacked_pred*<span class="number">0.70</span> + xgb_pred*<span class="number">0.15</span> + lgb_pred*<span class="number">0.15</span></span><br><span class="line"><span class="comment">#生成提交文件</span></span><br><span class="line">sub = pd.DataFrame()</span><br><span class="line">sub[<span class="string">&#x27;Id&#x27;</span>] = test_ID</span><br><span class="line">sub[<span class="string">&#x27;SalePrice&#x27;</span>] = ensemble</span><br><span class="line">sub.to_csv(<span class="string">&#x27;submission.csv&#x27;</span>,index=<span class="literal">False</span>)</span><br></pre></td></tr></table></figure>
<p>结果<br>0.07330605313530042<br>RMSLE score on train data:<br>0.07614183169332166<br>提交到kaggle里看看。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/31/17.png"><br>改进蛮大，排名401，进前10%了。<br>本文代码： <a target="_blank" rel="noopener" href="https://github.com/zwdnet/MyQuant/tree/master/39">https://github.com/zwdnet/MyQuant/tree/master/39</a></p>
<p>对于模型集成，还不太明白，下次专门研究下这个问题。<br>参考文献<br>[1]<a target="_blank" rel="noopener" href="https://www.kaggle.com/serigne/stacked-regressions-top-4-on-leaderboard">https://www.kaggle.com/serigne/stacked-regressions-top-4-on-leaderboard</a></p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/" rel="tag"># 机器学习</a>
          
            <a href="/tags/kaggle/" rel="tag"># kaggle</a>
          
            <a href="/tags/%E5%AE%9E%E4%BE%8B/" rel="tag"># 实例</a>
          
            <a href="/tags/%E5%9B%9E%E5%BD%92%E7%AE%97%E6%B3%95/" rel="tag"># 回归算法</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/04/07/%E9%94%90%E8%AF%BB%E4%BC%9A%E5%85%AC%E5%BC%80%E8%AF%BE%E3%80%8A%E5%90%8E%E7%89%99%E4%BA%8C%E7%B1%BB%E6%B4%9E-%E6%A0%91%E8%84%82%E7%9B%B4%E6%8E%A5%E4%BF%AE%E5%A4%8D%E7%9A%84CBT%E6%8A%80%E6%9C%AF%E5%8F%8A%E5%88%86%E6%AE%B5CBT%E6%8A%80%E6%9C%AF%E3%80%8B%E7%AC%94%E8%AE%B0/" rel="next" title="锐读会公开课《后牙二类洞-树脂直接修复的CBT技术及分段CBT技术》笔记">
                <i class="fa fa-chevron-left"></i> 锐读会公开课《后牙二类洞-树脂直接修复的CBT技术及分段CBT技术》笔记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/04/11/%E4%BD%A0%E4%BC%9A%E5%A4%87%E7%89%99%E5%90%97%E2%80%94%E2%80%94%E4%BF%9D%E5%AD%98%E7%89%99%E4%BD%93%E7%BB%93%E6%9E%84/" rel="prev" title="你会备牙吗——保存牙体结构">
                你会备牙吗——保存牙体结构 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
